<?php
/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/16
 * Time: 14:06
 */

namespace app\api\controller;


use app\api\BaseController;
use app\common\model\Refundreturn;
use think\Lang;


/**
 * @title 用户订单
 */
class Userorder extends BaseController
{

    public function _initialize() {
        parent::_initialize();
        Lang::load(APP_PATH . 'home/lang/'.config('default_lang').'/memberorder.lang.php');
    }


    /**
     * @title 订单列表
     * @description
     * @author fuzz
     * @url /Userorder/select
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_sn 订单编号(搜索)
     * @param string query_start_date 开始时间(搜索)
     * @param string query_end_date 结束时间(搜索)
     * @param string state_type 订单状态
     * @return {"code":200,"msg":"succeess"}
     */
    public function select(){
        /*$order_model = new \app\common\model\Order();

        //搜索
        $condition = array();
        $condition['buyer_id'] = $this->user_id;

        $order_sn = input('param.order_sn');
        if ($order_sn != '') {
            $condition['order_sn'] = array('like','%'.$order_sn.'%');
        }
        $query_start_date = input('param.query_start_date');
        $query_end_date = input('param.query_end_date');
        $if_start_date = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_date);
        $if_end_date = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_date);
        $start_unixtime = $if_start_date ? strtotime($query_start_date) : null;
        $end_unixtime = $if_end_date ? strtotime($query_end_date) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        $state_type = input('param.state_type');
        if ($state_type != '') {
            $condition['order_state'] = str_replace(
                array('state_new', 'state_pay', 'state_send', 'state_success', 'state_noeval', 'state_cancel'), array(ORDER_STATE_NEW, ORDER_STATE_PAY, ORDER_STATE_SEND, ORDER_STATE_SUCCESS, ORDER_STATE_SUCCESS, ORDER_STATE_CANCEL),$state_type);
        }
        if ($state_type == 'state_noeval') {
            $condition['evaluation_state'] = 0;
            $condition['order_state'] = ORDER_STATE_SUCCESS;
        }

        //回收站
        $recycle = input('param.recycle');
        if ($recycle) {
            $condition['delete_state'] = 1;
        } else {
            $condition['delete_state'] = 0;
        }

        $order_list = $order_model->getOrderList($condition, 5, '*', 'order_id desc','', array('order_common','order_goods','ppintuanorder','store'));
        //p($order_list);die;
        $this->assign('show_page', $order_model->page_info->render());

        $refundreturn_model = new Refundreturn();
        $order_list = $refundreturn_model->getGoodsRefundList($order_list);

      //  p($order_list);die;
        //订单列表以支付单pay_sn分组显示
        $order_group_list = array();
        $order_pay_sn_array = array();
        foreach ($order_list as $order_id => $order) {
            //显示取消订单
            $order['if_cancel'] = $order_model->getOrderOperateState('buyer_cancel', $order);
            //显示退款取消订单
            $order['if_refund_cancel'] = $order_model->getOrderOperateState('refund_cancel', $order);
            //显示投诉
            $order['if_complain'] = $order_model->getOrderOperateState('complain', $order);
            //显示收货
            $order['if_receive'] = $order_model->getOrderOperateState('receive', $order);
            //显示锁定中
            $order['if_lock'] = $order_model->getOrderOperateState('lock', $order);
            //显示物流跟踪
            $order['if_deliver'] = $order_model->getOrderOperateState('deliver', $order);
            //显示评价
            $order['if_evaluation'] = $order_model->getOrderOperateState('evaluation', $order);
            //显示删除订单(放入回收站)
            $order['if_delete'] = $order_model->getOrderOperateState('delete', $order);
            //显示永久删除
            $order['if_drop'] = $order_model->getOrderOperateState('drop', $order);
            //显示还原订单
            $order['if_restore'] = $order_model->getOrderOperateState('restore', $order);

            foreach ($order['extend_order_goods'] as $value) {
                $value['goods_type_cn'] = get_order_goodstype($value['goods_type']);
                $value['goods_url'] = url('Goods/index', ['goods_id' => $value['goods_id']]);
                if ($value['goods_type'] == 5) {
                    $order['zengpin_list'][] = $value;
                } else {
                    $order['goods_list'][] = $value;
                }
            }

            if (empty($order['zengpin_list'])) {
                $order['goods_count'] = count($order['goods_list']);
            } else {
                $order['goods_count'] = count($order['goods_list']) + 1;
            }
            $order_group_list[$order['pay_sn']]['order_list'][] = $order;

            //如果有在线支付且未付款的订单则显示合并付款链接
            if ($order['order_state'] == ORDER_STATE_NEW) {
                if (!isset($order_group_list[$order['pay_sn']]['pay_amount'])) {
                    $order_group_list[$order['pay_sn']]['pay_amount'] = 0;
                }
                $order_group_list[$order['pay_sn']]['pay_amount'] += $order['order_amount'] - $order['pd_amount'] - $order['rcb_amount'];
            }
            $order_group_list[$order['pay_sn']]['add_time'] = $order['add_time'];

            //记录一下pay_sn，后面需要查询支付单表
            $order_pay_sn_array[] = $order['pay_sn'];
        }
      //
        //取得这些订单下的支付单列表
        $condition = array('pay_sn' => array('in', array_unique($order_pay_sn_array)));
        $order_pay_list = $order_model->getOrderpayList($condition,'*','','pay_sn');
        foreach ($order_group_list as $pay_sn => $pay_info) {
            $order_group_list[$pay_sn]['pay_info'] = isset($order_pay_list[$pay_sn])?$order_pay_list[$pay_sn]:'';
        }
        $result = array();
      //  p($order_group_list);die;
        foreach ($order_group_list as $key=>$value){
            $result[] = $value;
        }
        //p($result);die;
        $app_order_list = db('app_order')->where('user_id',$this->user_id)->order('create_time','desc')->select();
        foreach($app_order_list as $k=>$v){
            $ids = explode(',',$app_order_list[$k]['order_ids']);
                foreach($result as $key=>$val){
                    $new_array[$k]['order_sn'] = $v['order_sn'];
                    $new_array[$k]['create_time'] = $v['create_time'];

                    if(in_array($result[$key]['order_list']['0']['order_id'],$ids )){
                        $new_array[$k]['order_list'][] = $result[$key]['order_list']['0'];
                        $new_array[$k]['goods_list'][] = $result[$key]['order_list']['0']['goods_list'];
                    }

            }
        }*/
     //   p($new_array);die;

        $order_status = input('order_status','-1');   //-1:全部 '0：待付款 1：待收货 2：已完成 3：已取消';
        if($order_status=='-1'){
            $app_order_list = db('app_order')->where('user_id',$this->user_id)->where('user_id',$this->user_id)->order('create_time','desc')->select();
        }else{
            $app_order_list = db('app_order')->where('user_id',$this->user_id)->where('order_status',$order_status)->order('create_time','desc')->select();
        }
       if(empty($app_order_list)){
           $app_order_list = array();
           json_success_return($app_order_list);
       }
       
      $config = db('config')->where('code', 'qiniu_http')->find();
       foreach($app_order_list as  $k=>$v){

           $app_order_list[$k]['goods_list'] = db('ordergoods')->where('rec_id','in',$v['ordergoods_ids'])->select();
           $app_order_list[$k]['order_list'] = db('order')->where('order_id','in',$v['order_ids'])->select();
       }

       foreach($app_order_list as  $k=>$v){
        
           foreach($v['goods_list'] as  $ke=>$va){

           $app_order_list[$k]['goods_list'][$ke]['goods_image_url'] = $config['value'].'/'.$va['goods_image'];
       }
       } 
        json_success_return($app_order_list);
    }

    /**
     * @title 订单详情
     * @description
     * @author fuzz
     * @url /Userorder/detail
         * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @return {"code":200,"msg":"succeess"}
     */
    public function detail(){
        /*$order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            return json_fail_return(lang('member_order_none_exist'));
        }
        $order_model = new \app\common\model\Order();
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->user_id;
        $order_info = $order_model->getOrderInfo($condition, array('order_goods', 'order_common', 'store'));
        if (empty($order_info) || $order_info['delete_state'] == ORDER_DEL_STATE_DROP) {
            return json_fail_return(lang('member_order_none_exist'));
        }

        $refundreturn_model = new Refundreturn();
        $order_list = array();
        $order_list[$order_id] = $order_info;
        $order_list = $refundreturn_model->getGoodsRefundList($order_list, 1); //订单商品的退款退货显示
        $order_info = $order_list[$order_id];
        $refund_all = isset($order_info['refund_list'][0]) ? $order_info['refund_list'][0] : '';
        if (!empty($refund_all) && $refund_all['seller_state'] < 3) {//订单全部退款商家审核状态:1为待审核,2为同意,3为不同意
            return $order_info['refund_all']=$refund_all;
        }

        $express = rkcache('express', true);
        $express_info['express_code'] = $express[$order_info['extend_order_common']['shipping_express_id']]['express_code'];
        $express_info['express_name'] = $express[$order_info['extend_order_common']['shipping_express_id']]['express_name'];
        $express_info['express_url'] = $express[$order_info['extend_order_common']['shipping_express_id']]['express_url'];
        $order_info['express_info'] = $express_info;
        //显示锁定中
        $order_info['if_lock'] = $order_model->getOrderOperateState('lock', $order_info);

        //显示取消订单
        $order_info['if_cancel'] = $order_model->getOrderOperateState('buyer_cancel', $order_info);

        //显示退款取消订单
        $order_info['if_refund_cancel'] = $order_model->getOrderOperateState('refund_cancel', $order_info);

        //显示投诉
        $order_info['if_complain'] = $order_model->getOrderOperateState('complain', $order_info);

        //显示收货
        $order_info['if_receive'] = $order_model->getOrderOperateState('receive', $order_info);

        //显示物流跟踪
        $order_info['if_deliver'] = $order_model->getOrderOperateState('deliver', $order_info);

        //显示评价
        $order_info['if_evaluation'] = $order_model->getOrderOperateState('evaluation', $order_info);

        //显示系统自动取消订单日期
        if ($order_info['order_state'] == ORDER_STATE_NEW) {
            $order_info['order_cancel_day'] = $order_info['add_time'] + config('order_auto_cancel_day') * 24 * 3600;
        }

        //显示快递信息
        if ($order_info['shipping_code'] != '') {
            $express = rkcache('express', true);
            $order_info['express_info']['express_code'] = $express[$order_info['extend_order_common']['shipping_express_id']]['express_code'];
            $order_info['express_info']['express_name'] = $express[$order_info['extend_order_common']['shipping_express_id']]['express_name'];
            $order_info['express_info']['express_url'] = $express[$order_info['extend_order_common']['shipping_express_id']]['express_url'];
        }

        //显示系统自动收获时间
        if ($order_info['order_state'] == ORDER_STATE_SEND) {
            $order_info['order_confirm_day'] = $order_info['delay_time'] + config('order_auto_receive_day') * 24 * 3600;
        }

        //如果订单已取消，取得取消原因、时间，操作人
        if ($order_info['order_state'] == ORDER_STATE_CANCEL) {
            $order_info['close_info'] = $order_model->getOrderlogInfo(array('order_id' => $order_info['order_id']), 'log_id desc');
        }

        foreach ($order_info['extend_order_goods'] as $value) {
            $value['image_240_url'] = goods_cthumb($value['goods_image'], 240, $value['store_id']);
            $value['goods_type_cn'] = get_order_goodstype($value['goods_type']);
            $value['goods_url'] = url('Goods/index', ['goods_id' => $value['goods_id']]);
            if ($value['goods_type'] == 5) {
                $order_info['zengpin_list'][] = $value;
            } else {
                $order_info['goods_list'][] = $value;
            }
        }
        if (empty($order_info['zengpin_list'])) {
            $order_info['goods_count'] = count($order_info['goods_list']);
        } else {
            $order_info['goods_count'] = count($order_info['goods_list']) + 1;
        }
        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = (new \app\common\model\Address())->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $order_info['daddress_info'] = $daddress_info;
        }

        json_success_return($order_info);*/
        $apporder_id = intval(input('param.apporder_id'));
        if ($apporder_id <= 0) {
            return json_fail_return(lang('member_order_none_exist'));
        }

        $app_order_list = db('app_order')->where('user_id',$this->user_id)->where('app_order_id',$apporder_id)->find();
       // p($app_order_list);die;
         if(empty($app_order_list)){
             json_fail_return('订单id信息错误');
         }
         $app_order_list['order_list'] = db('order')->where('order_id','in',$app_order_list['order_ids'])->select();

         foreach($app_order_list['order_list'] as  $k=>$v){
             $app_order_list['order_list'][$k]['goods_list'] = db('ordergoods')->where('order_id',$v['order_id'])->select();
         }
       
       $config = db('config')->where('code', 'qiniu_http')->find();
      // p($app_order_list);die;
          foreach($app_order_list['order_list'] as  $k=>$v){
        
           foreach($v['goods_list'] as  $ke=>$va){

           $app_order_list['order_list'][$k]['goods_list'][$ke]['goods_image_url'] = $config['value'].'/'.$va['goods_image'];
           
           $goods_info = db('goods')->where('goods_id',$va['goods_id'])->find();

           $app_order_list['order_list'][$k]['goods_list'][$ke]['change_goods'] = $goods_info['change_goods'];

           $app_order_list['order_list'][$k]['goods_list'][$ke]['return_goods'] = $goods_info['return_goods'];
           $app_order_list['order_list'][$k]['goods_list'][$ke]['change_goods'] = $goods_info['change_goods'];
           $app_order_list['order_list'][$k]['goods_list'][$ke]['course_id'] = $goods_info['course_id'];

       }
       } 
        json_success_return($app_order_list);
    }



    /**
     * @title 申请退换货接口
     * @description
     * @author fuzz
     * @url /Userorder/return_apply
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type    2：退货 3：换货
     * @return {"code":200,"msg":"succeess"}
     */
    public function return_apply() {
        $order_id = intval(input('param.order_id'));
        $apply_type = input('param.apply_type');
        $apply_reason = input('param.apply_reason');
        $apply_explain = input('param.apply_explain');
        $apply_images = input('param.apply_images');
        $express_id = input('param.express_id');
        $invoice_no = input('param.invoice_no');
        $goods_id = input('param.goods_id');
        
        if(empty($apply_type) || empty($order_id)){
            return json_fail_return('参数错误');
        }

        //判断当前订单是否可以操作退换货
        $status = db('order')->where(['order_id'=>$order_id])->find();

        if($status['order_state'] >= 40 || $status['order_state'] <= 10){
            return json_fail_return('无权操作');
        }

        //判断当前订单的商品是否包含退换货
        $order_model = new \app\common\model\Order();
        $condition = array();
        $condition['o.order_id'] = $order_id;
        $condition['o.buyer_id'] = $this->user_id;
        $order_info = $order_model->getReturnOrderInfo($condition);
        
        $goods_model = new \app\common\model\Goods();
        $return_info = $goods_model->getReturnInfo($order_info['goods_id']);
        //退换货
        if($apply_type == 2){
            //判断是否包含退货
            if($return_info['return_goods'] == 0){
                return json_fail_return('当前订单不支持退货');
            }
        }else{
            //判断是否包含退货
            if($return_info['change_goods'] == 0){
                return json_fail_return('当前订单不支持换货');
            }
        }

        //入库
        $result = $order_model->addReturnOrder($order_id,$apply_type,$apply_reason,$apply_explain,$apply_images,$this->user_id,$order_info,$express_id,$invoice_no,$goods_id);
           json_success_return();
    }

    /**
     * @title 大订单退款接口
     * @description
     * @author fuzz
     * @url /Userorder/big_refund
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     */
    public function big_refund() {
        $app_order_id = intval(input('param.app_order_id'));
        $apply_type = input('param.apply_type');
        $apply_reason = input('param.apply_reason');
        $apply_explain = input('param.apply_explain');
        $apply_images = input('param.apply_images');

        if(empty($apply_type) || empty($app_order_id)){
            return json_fail_return('参数错误');
        }

        $app_order_info = db('app_order')->where(['app_order_id'=>$app_order_id])->find();

        if($app_order_info['order_status'] <= 0 || $app_order_info['order_status'] >= 2 ){
            return json_fail_return('无权操作');
        }
        
        $order_model = new \app\common\model\Order();
        //入库
        $result = $order_model->addBigRefundOrder($app_order_id,$apply_type,$apply_reason,$apply_explain,$apply_images,$this->user_id,$app_order_info);
        if(!empty($result)){
           json_success_return();
        }else{
           json_fail_return();
        }
    }

     /**
     * @title 大订单取消退款接口
     * @description
     * @author fuzz
     * @url /Userorder/big_refund
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     */
    public function cancel_refund() {
        $app_order_id = intval(input('param.app_order_id'));

        if(empty($app_order_id)){
            return json_fail_return('参数错误');
        }

        $app_order_info = db('app_order')->where(['app_order_id'=>$app_order_id])->find();

        $order_ids = explode(',',$app_order_info['order_ids']);
        
        db('refundreturn')->where(['app_order_id'=>$app_order_id])->delete();
        foreach ($order_ids as $key => $value) {
            $result = db('order')->where(['order_id'=>$value])->update(['refund_state'=>0]);
        }
        json_success_return();
       
    }

    /**
     * @title 取消退换货接口
     * @description
     * @author fuzz
     * @url /Userorder/cancel_apply
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type    1 退款   2 退换货
     * @return {"code":200,"msg":"succeess"}
     */
    public function cancel_apply() {
        $order_id = intval(input('param.order_id'));
        $apply_type = intval(input('param.apply_type'));
        $goods_id = intval(input('param.goods_id'));
        if(empty($order_id) || empty($apply_type)){
            return json_fail_return('参数错误');
        }
      
        db('refundreturn')->where(['order_id'=>$order_id])->delete();
        if($apply_type == 1){
            //退款
            db('order')->where(['order_id'=>$order_id])->update(['refund_state'=>0]);
            db('ordergoods')->where(['order_id'=>$order_id])->update(['return_status'=>0]);
        }else{
            //退换货
            db('ordergoods')->where(['goods_id'=>$goods_id])->update(['return_status'=>0]);
        }
        
        json_success_return();
    }


    /**
     * @title 改变订单状态
     * @description
     * @author fuzz
     * @url /Userorder/detail
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string state_type 操作命令order_cancel取消订单order_receive收货order_recycle删除
     * @return {"code":200,"msg":"succeess"}
     */
    public function changeState() {
        $state_type = input('param.state_type');
        $order_id = intval(input('param.order_id'));
        $app_order_id = intval(input('param.app_order_id'));
        
        if(empty($state_type) || empty($order_id)){
            return json_fail_return('参数错误');
        }
        
        //获取订单详情
        $order_model = new \app\common\model\Order();
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->user_id;
        $order_info = $order_model->getOrderInfo($condition);
       
        //取消订单
        if ($state_type == 'order_cancel') {
            $result = $this->_order_cancel($order_info, input('post.'),$app_order_id);
        } else if ($state_type == 'order_receive') {
        //   收货 
            $result = $this->_order_receive($order_info, input('post.'),$app_order_id);
        } else if (in_array($state_type, array('order_delete', 'order_drop', 'order_restore'))) {
            $result = $this->_order_recycle($order_info, input('post.'));
        } else {
            exit();
        }
        // if (!$result['code']) {
        //     json_success_return($result['msg']);
        // } else {

        //     json_fail_return($result['msg']);
        // }
        if (!$result['code']) {
            json_fail_return($result['msg']);
        } else {
           json_success_return($result['msg']);
        }
    }


    /**
     * 回收站
     */
    private function _order_recycle($order_info, $get) {
        $order_model = new \app\common\model\Order();
        $logic_order = new \app\common\logic\Order();
        $state_type = str_replace(array('order_delete', 'order_drop', 'order_restore'), array('delete', 'drop', 'restore'), input('param.state_type'));
        $if_allow = $order_model->getOrderOperateState($state_type, $order_info);
        if (!$if_allow) {
            return ds_callback(false, lang('have_right_operate'));
        }

        return $logic_order->changeOrderStateRecycle($order_info, 'buyer', $state_type);
    }

    /**
     * 取消订单
     */
    private function _order_cancel($order_info, $post,$app_order_id) {
        $order_model = new \app\common\model\Order();
        $logic_order = new \app\common\logic\Order();
        $if_allow = $order_model->getOrderOperateState('buyer_cancel', $order_info);
        if (!$if_allow) {
            return ds_callback(false,  lang('have_right_operate'));
        }

        //$msg = $post['state_info1'] != '' ? $post['state_info1'] : $post['state_info'];
        // return $logic_order->changeOrderStateCancel($order_info, 'buyer', $this->user_id, $msg);
        return $logic_order->changeOrderStateCancel($order_info, 'buyer', $this->user_id,$app_order_id);
    }

    /**
     * 收货
     */
    private function _order_receive($order_info, $post,$app_order_id) {
        $order_model = new \app\common\model\Order();
        $logic_order = new \app\common\logic\Order();
        $if_allow = $order_model->getOrderOperateState('receive', $order_info);
        if (!$if_allow) {
            return ds_callback(false,  lang('have_right_operate'));
        }

        return $logic_order->changeOrderStateReceive($order_info, 'buyer', $this->user_id,$app_order_id);
    }

    public function refund(Refundreturn $refundreturn_model) {
        $condition = array();
        $reason_list = $refundreturn_model->getReasonList($condition); //退款退货原因
        $this->assign('reason_list', $reason_list);
        $order_id = intval(input('param.order_id'));
        $goods_id = intval(input('param.goods_id')); //订单商品表编号
        if ($order_id < 1 || $goods_id < 1) {//参数验证
            return json_fail_return(lang('wrong_argument'));
        }
        $condition = array();
        $condition['buyer_id'] = $this->user_id;
        $condition['order_id'] = $order_id;

        $order = $refundreturn_model->getRightOrderList($condition, $goods_id);
        $order_id = $order['order_id'];
        $order_amount = $order['order_amount']; //订单金额
        $order_refund_amount = $order['refund_amount']; //订单退款金额
        $goods_list = $order['goods_list'];
        $goods = $goods_list[0];
        $goods_pay_price = $goods['goods_pay_price']; //商品实际成交价
        if ($order_amount < ($goods_pay_price + $order_refund_amount)) {
            $goods_pay_price = $order_amount - $order_refund_amount;
            $goods['goods_pay_price'] = $goods_pay_price;
        }
        $result = array(
            'goods' =>$goods,
            'order' =>$order,
            'store' =>$order['extend_store'],
            'order_common' =>$order['extend_order_common'],
            'goods_list' =>$order['goods_list'],
        );


        $goods_id = $goods['rec_id'];
        $condition = array();
        $condition['buyer_id'] = $order['buyer_id'];
        $condition['order_id'] = $order['order_id'];
        $condition['order_goods_id'] = $goods_id;
        $condition['seller_state'] = array('lt', '3');
        $refund_list = $refundreturn_model->getRefundreturnList($condition);
        $refund = array();
        if (!empty($refund_list) && is_array($refund_list)) {
            $refund = $refund_list[0];
        }
        $refund_state = $refundreturn_model->getRefundState($order); //根据订单状态判断是否可以退款退货

        if ((isset($refund['refund_id']) && $refund['refund_id'] > 0) || $refund_state != 1) {//检查订单状态,防止页面刷新不及时造成数据错误
            return json_fail_return(lang('wrong_argument'));
        }
        if (request()->isPost() && $goods_id > 0) {
            $refund_array = array();
            $refund_amount = floatval(input('post.refund_amount')); //退款金额
            if (($refund_amount < 0) || ($refund_amount > $goods_pay_price)) {
                $refund_amount = $goods_pay_price;
            }
            $goods_num = intval(input('post.goods_num')); //退货数量
            if (($goods_num < 0) || ($goods_num > $goods['goods_num'])) {
                $goods_num = 1;
            }
            $refund_array['reason_info'] = '';
            $reason_id = intval(input('post.reason_id')); //退货退款原因
            $refund_array['reason_id'] = $reason_id;
            $reason_array = array();
            $reason_array['reason_info'] = lang('other');
            $reason_list[0] = $reason_array;
            if (!empty($reason_list[$reason_id])) {
                $reason_array = $reason_list[$reason_id];
                $refund_array['reason_info'] = $reason_array['reason_info'];
            }

            $pic_array = array();
            $pic_array['buyer'] = $this->upload_pic(); //上传凭证
            $info = serialize($pic_array);
            $refund_array['pic_info'] = $info;

            $trade_model = model('trade');
            $order_shipped = $trade_model->getOrderState('order_shipped'); //订单状态30:已发货
            if ($order['order_state'] == $order_shipped) {
                $refund_array['order_lock'] = '2'; //锁定类型:1为不用锁定,2为需要锁定
            }else{
                $refund_array['order_lock'] = '1';
            }

            $refund_array['refund_type'] = input('post.refund_type'); //类型:1为退款,2为退货
            $show_url = url('Memberreturn/index');
            $refund_array['return_type'] = '2'; //退货类型:1为不用退货,2为需要退货
            if ($refund_array['refund_type'] != '2') {
                $refund_array['refund_type'] = '1';
                $refund_array['return_type'] = '1';
                $show_url = url('Memberrefund/index');
            }
            $refund_array['seller_state'] = '1'; //状态:1为待审核,2为同意,3为不同意
            $refund_array['refund_amount'] = ds_price_format($refund_amount);
            $refund_array['goods_num'] = $goods_num;
            $refund_array['buyer_message'] = input('post.buyer_message');
            $refund_array['add_time'] = time();
            $state = $refundreturn_model->addRefundreturn($refund_array, $order, $goods);

            if ($state) {
                if ($order['order_state'] == $order_shipped) {
                    $refundreturn_model->editOrderLock($order_id);
                }
                return json_success_return([],'退款成功');
            } else {
                return json_fail_return('退款失败');
            }
        } else {
            $result['state_array'] = $this->getRefundStateArray();
            return json_success_return($result);
        }
    }

    function getRefundStateArray($type = 'all') {
        $state_array = array(
            '1' => lang('refund_state_confirm'),
            '2' => lang('refund_state_yes'),
            '3' => lang('refund_state_no')
        ); //卖家处理状态:1为待审核,2为同意,3为不同意

        $admin_array = array(
            '1' => lang('in_processing'),
            '2' => lang('to_be_processed'),
            '3' => lang('has_been_completed')
        ); //确认状态:1为买家或卖家处理中,2为待平台管理员处理,3为退款退货已完成

        $state_data = array(
            'seller' => $state_array,
            'admin' => $admin_array
        );
        if ($type == 'all') {
            return $state_data; //返回所有
        }
        return $state_data[$type];
    }

}